<?php

namespace app\shop\controller\product;

use think\Controller;
use think\Request;

class Cart extends Controller
{
    protected $CartModel;
    protected $BusinessModel;
    protected $ProductModel;
    protected $RelationModel;
    protected $AttributeModel;

    public function __construct()
    {
        parent::__construct();

        $this->CartModel = model('product.Cart');
        $this->BusinessModel = model('business.Business');
        $this->ProductModel = model('product.Product');
        $this->RelationModel = model('product.attribute.Relation');
        $this->AttributeModel = model('product.attribute.Attribute');
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $proid = $this->request->param('proid', 0, 'trim');
            $num = $this->request->param('num', 0, 'trim');
            $source = $this->request->param('source', 0, 'trim');
            $relationids = $this->request->param('relationids/a', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $product = $this->ProductModel->find($proid);

            if (!$product) {
                $this->error('商品不存在');
            }

            if ($product['stock'] < $num && $product['stock'] <= 0) {
                $this->error('商品库存不存在');
            }

            // 组装好数据
            $data = [
                'busid' => $busid,
                'proid' => $proid,
                'nums' => $num,
                'source' => $source
            ];


            // 如果商品没有规格
            if (empty($relationids)) {
                $data['price'] = $product['price'];
                $data['total'] = bcmul($product['price'], $num, 2);
                $data['attrs'] = null;
            } else {
                $relationData = $this->RelationModel->with(['attribute'])->where(['relation.id' => ['IN', $relationids]])->select();
                $price = $product['price'];

                $attrs = [];

                if ($relationData) {
                    foreach ($relationData as $item) {
                        $attrs[] = [
                            'name' => $item['attribute'] ? $item['attribute']['name'] : '未知属性',
                            'value' => $item['value'],
                            'price' => $item['price']
                        ];

                        $price = bcadd($price, $item['price'], 2);
                    }
                }

                $data['price'] = $price;
                $data['total'] = bcmul($price, $num, 2);
                $data['attrs'] = json_encode($attrs);
            }

            $cart = $this->CartModel->where(['busid' => $busid, 'proid' => $proid, 'attrs' => $data['attrs'], 'source' => $source])->find();

            if ($cart) {
                $nums = bcadd($cart['nums'], $num);

                $updateData = [
                    'id' => $cart['id'],
                    'nums' => $nums,
                    'price' => $cart['price'],
                    'total' => bcmul($nums, $cart['price'], 2),
                    'source' => $source
                ];

                $result = $this->CartModel->validate('common/product/Cart.edit')->isUpdate(true)->save($updateData);
            } else {
                $result = $this->CartModel->validate('common/product/Cart')->save($data);
            }

            $cartlist = $this->CartModel->where(['busid' => $busid, 'proid' => $proid, 'attrs' => $data['attrs'], 'source' => $source])->find();

            if ($result === false) {
                $this->error($this->CartModel->getError());
            } else {
                $this->success('加入购物车成功', null, $cartlist);
            }
        }
    }

    // 获取当前登录用户的购物车所有的数据
    public function index()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $source = $this->request->param('source', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $CartList = $this->CartModel->with(['product'])->where(['busid' => $busid, 'source' => $source])->order('id desc')->select();

            if ($CartList) {
                $this->success('查询购物车数据成功', null, $CartList);
            } else {
                $this->error('暂无购物车记录', null, []);
            }
        }
    }


    public function edit()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $nums = $this->request->param('nums', 1, 'trim');
            $cartid = $this->request->param('cartid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $cart = $this->CartModel->where(['busid' => $busid, 'id' => $cartid])->find();

            if (!$cart) {
                $this->error('该购物车记录不存在');
            }

            $data = [
                'id' => $cartid,
                'nums' => $nums,
                'price' => $cart['price'],
                'total' => bcmul($cart['price'], $nums, 2)
            ];

            $result = $this->CartModel->validate('common/product/Cart.edit')->isUpdate(true)->save($data);

            if ($result === false) {
                $this->error($this->CartModel->getError());
            } else {
                $this->success('更新购物车记录成功');
            }
        }
    }

    //删除
    public function del()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $cartid = $this->request->param('cartids', 0, 'trim');
            $source = $this->request->param('source', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $cart = $this->CartModel->where(['busid' => $busid, 'id' => $cartid, 'source' => $source])->find();

            if (!$cart) {
                $this->error('该购物车记录不存在');
            }

            $result = $cart->delete();

            if ($result === false) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功');
            }
        }
    }

}
